package viz.example.webviewdemo

import android.os.Build
import android.os.Bundle
import android.util.Log
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.InputStream


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //注册事件
        EventBus.getDefault().register(this)
        webView.settings.javaScriptEnabled = true
        webView.settings.domStorageEnabled = true
        webView.settings.databaseEnabled = true
        webView.settings.loadWithOverviewMode = true
        webView.settings.allowUniversalAccessFromFileURLs = true
        webView.settings.allowFileAccessFromFileURLs = true
        webView.settings.allowFileAccess = true
        webView.addJavascriptInterface(
            MyJavascriptInterface(this.applicationContext),
            "nativePlugin"
        )
        //解决网页不显示的代码
        webView.webViewClient = object : WebViewClient() {
            override fun shouldInterceptRequest(
                view: WebView?,
                request: WebResourceRequest?
            ): WebResourceResponse? {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (request != null && request.url != null && request.url.path != null) {
                        Log.i("WebViewDemo", request.url.toString())
                        if(request.url.toString() == "file:///#/") {
                            return super.shouldInterceptRequest(view, "file:///android_asset/www/index.html/#/")
                        }
                        if (!request.url.toString().startsWith("file:///android_asset/www/") && !request.url.toString().startsWith("http://") && !request.url.toString().startsWith("https://")) {
                            try {
                                return getUtf8EncodedJsWebResourceResponse(assets.open("www${request.url.path}"))
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                }
                return super.shouldInterceptRequest(view, request)
            }

            override fun shouldInterceptRequest(
                view: WebView?,
                url: String?
            ): WebResourceResponse? {
                if(url != null && url == "file:///#/") {
                    return super.shouldInterceptRequest(view, "file:///android_asset/www/index.html/#/")
                }
                if (url != null && !url.startsWith("file:///android_asset/www/") && !url.startsWith("http://") && !url.startsWith("https://")) {
                    return getUtf8EncodedJsWebResourceResponse(assets.open("www${url}"))
                }
                return super.shouldInterceptRequest(view, url)
            }

            private fun getUtf8EncodedJsWebResourceResponse(data: InputStream): WebResourceResponse? {
                return WebResourceResponse("text/javascript", "UTF-8", data)
            }
        }

        webView.loadUrl("file:///android_asset/www/index.html")
    }

    override fun onDestroy() {
        super.onDestroy()
        //取消注册事件
        EventBus.getDefault().unregister(this)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_TAKE_PICTURE:
                    EventBus.getDefault().postSticky(JsEvent("test", si))
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, intent)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun jsCallBack(jsEvent: JsEvent) {
        webView.loadUrl("javascript:WebApp.JSCallBack(${jsEvent.index}, '${jsEvent.data}')")
    }
}